<?php //if (!defined('TL_ROOT')) die('You cannot access this file directly!');

/**
 * Contao Open Source CMS
 * Copyright (C) 2005-2011 Leo Feyer
 *
 * Formerly known as TYPOlight Open Source CMS.
 *
 * This program is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program. If not, please visit the Free
 * Software Foundation website at <http://www.gnu.org/licenses/>.
 *
 * PHP version 5
 * @copyright  Stefan Melz 2012 
 * @author     Stefan Melz 
 * @package    z_smpdf 
 * @license    GNU 
 * @filesource
 */


/**
 * Class z_smpdf 
 *
 * @copyright  Stefan Melz 2012 
 * @author     Stefan Melz 
 * @package    Controller
 */
class z_smpdf extends Module
{

	/**
	 * Template
	 * @var string
	 */
	protected $strTemplate = '';


	/**
	 * Display a wildcard in the back end
	 * @return string
	 */
	public function generate()
	{
		if (TL_MODE == 'BE')
		{
			$objTemplate = new BackendTemplate('be_wildcard');

			$objTemplate->wildcard = '### PDF Generator ###';
			$objTemplate->id = $this->id;
			$objTemplate->link = $this->name;
			$objTemplate->href = 'contao/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id=' . $this->id;

			return $objTemplate->parse();
		}

		return parent::generate();
	}


    /**
     * read all taxonomy labels
     * @return array
     */
    public function getTaxArray()
    {
        $taxLabels = $this->Database->prepare("select * from tl_taxonomy")
            ->execute();
        while($taxLabels->next())
        {
            $taxLabelssum[$taxLabels->id] = array
            (
            'name'           => $taxLabels->name,
            'name_en'        => $taxLabels->name_en,
            'pid'            => $taxLabels->pid,
            'alias'          => $taxLabels->alias,
            'trennzeichen'    => $taxLabels->trennzeichen,
            );
        }
        return $taxLabelssum;
    }


    /**
     * dbabfrage fuer Namensgenerierung
     * @param $taxid
     * @param $taxArray
     * @return mixed
     */
    public function getTaxLabel($taxid,$taxArray)
	{
        if($GLOBALS['TL_LANGUAGE'] != 'de')
        {
            $taxLabel = $taxArray[$taxid]['name_'.$GLOBALS['TL_LANGUAGE'].''];
        }
        else
        {
            $taxLabel = $taxArray[$taxid]['name'];
        }
        return $taxLabel;
	}


    /**
     * taxonomy seperator auslesen
     * @param $taxid
     * @param $taxArray
     * @return string
     */
    public function getTaxSeperator($taxid,$taxArray)
    {
        $trennzeichen =  $taxArray[$taxArray[$taxid]['pid']]['trennzeichen'];
        return "$trennzeichen ";
    }


    /**
     * parentname aus taxonomy array auslesen
     * @param $taxid
     * @param $taxArray
     * @return mixed
     */
    public function getParentName($taxid,$taxArray)
    {
        $pid = $taxArray[$taxid]['pid'];
        return $this->getTaxLabel($pid,$taxArray);
    }


    /**
     * icon ausgaben erstellen
     * @param $object
     * @return string
     */
    public function getIcons($object)
    {
        foreach (explode(',',$object) as $item)
        {
            //icon 1
            if (($item == '211') and $icon1 != true)
            {
                $icon[] = '<img src="tl_files/solana/pdf/Icon_1.png"/>';
                $icon1 = true;
            }
            //icon 2
            if (($item == '199' or $item == '201' or $item == '202' or $item == '206') and $icon2 != true)
            {
                $icon[] = '<img src="tl_files/solana/pdf/Icon_2.png"/>';
                $icon2 = true;
            }
            //icon 3
            if (($item == '209') and $icon3 != true)
            {
                $icon[] = '<img src="tl_files/solana/pdf/Icon_3.png"/>';
                $icon3 = true;
            }
            //icon 4
            if (($item == '203') and $icon4 != true)
            {
                $icon[] = '<img src="tl_files/solana/pdf/Icon_4.png"/>';
                $icon4 = true;
            }
            //icon 5
            if (($item == '213') and $icon5 != true)
            {
                $icon[] = '<img src="tl_files/solana/pdf/Icon_5.png"/>';
                $icon5 = true;
            }
            //icon 7
            if (($item == '205')and $icon7 != true)
            {
                $icon[] = '<img src="tl_files/solana/pdf/Icon_7.png"/>';
                $icon7 = true;
            }
        }
        if(count($icons) > 0)
        {
            return implode($icon);
        }
        else
        {
            return false;
        }
    }


    /**
     * label aus taxonomy auslesen
     * @param $part
     * @param $count
     * @return string
     */
    public function generateRow($part,$count)
	{
		$i = 0;
		$class= "";
		foreach ($part as $item)
		{
			$names = Array();
			$singleValue = explode(',',$item);
			foreach ($singleValue as $taxNames)
			{
				$names[] = ucfirst(strtolower($this->getTaxLabel($taxNames,$this->getTaxArray())));
                //value to get parent id
                $id = $taxNames;
			}
		    //reihe ermitteln
		    if($i == $count-1) {$class='last';}else{$class='';}
            $trennzeichen = $this->getTaxSeperator($id,$this->getTaxArray());
		    $row[] = '<tr class="valuerow">
						<td class="label ' .$class. '" width="105">
						'.ucfirst(strtolower($this->getParentName($id,$this->getTaxArray()))).'
						</td>
						<td class="value ' .$class. '" width="95">
						'.implode($trennzeichen,$names).'
						</td>
					</tr>';
		    $i++;
		}
		return implode($row);
	}	
	
	
	/**
	 * Generate PDF
	 */
	protected function compile()
	{
		if($this->Input->get('pdf') == 'create')
		{
			//getdata from catalog
			if($this->Input->get('id'))
			{
				$dataobject = $this->Database->prepare("Select * from solana_sorten where id = ?")->execute($this->Input->get('id'));
			}
            //set description varaibles for template
            if($GLOBALS['TL_LANGUAGE'] != 'de')
            {
                $description = $dataobject->description_en;
            }
            else
            {
                $description = $dataobject->description_de;
            }

		
			//create pdf
			if ($dataobject->numRows > 0)
			{

                // generate icons
                // $icons = $this->getIcons($dataobject->verwertungsrichtung);
                //generate name
                $name = '<h1>&nbsp;'.strtoupper($dataobject->name_de).'&nbsp;</h1>';
				//import pdf framework
				require_once('plugins/smpdf/tcpdf.php');
                //datahandling
                require_once('templates/solana_de/varhandling_pdf.php');
                //main template pdf
                require_once('templates/solana_de/pdftemplate.php');
                // Print text using writeHTMLCell()
				// create new PDF document
				$pdf = new mypdfhf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
                $droidserif = $pdf->addTTFfont('plugins/smpdf/Droid_Serif/DroidSerif.ttf', 'TrueTypeUnicode', '', 32);
                $pdf->SetFont($droidserif, '', 20, '', 'false');


				// set document information
				$pdf->SetCreator(PDF_CREATOR);
				$pdf->SetAuthor(PDF_AUTHOR);
				$pdf->SetTitle(strtoupper($dataobject->name_de));
				$pdf->SetSubject('Solana Kartoffelsorte');
				$pdf->SetKeywords('Solana GmbH & co. KG, Kartoffelzuechtung');
										
				// remove/add default header/footer
                $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 001', PDF_HEADER_STRING);
							
				//set margins
				$pdf->SetMargins(10, 85, 10);
				$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
				$pdf->SetFooterMargin(15);
				//set auto page breaks
				$pdf->SetAutoPageBreak(TRUE, 23);
				//set some language-dependent strings
				$pdf->setLanguageArray($l);
				
				// ---------------------------------------------------------
				
				// set default font subsetting mode
				$pdf->setFontSubsetting(true);
				// Set font
				$pdf->SetFont('helvetica', '', 14, '', true);
				// Add a page
				// This method has several options, check the source code documentation for more information.
				$pdf->AddPage();
				
				//produktbild setzen
				if($dataobject->image)
				{ 
					$pdf->Image($dataobject->image, 45, 3, 100, 80, 'jpg', '', '', 2, 300, '', false, false, 0, true, false, false);
				}

				// --- Rotation Name --------------------------------------------
                $pdf->StartTransform();
                //$pdf->SetFont($droidserif, '', 28, '', 'false');
                $pdf->SetFont('helvetica', '', 28, '', 'false');
                $pdf->Rotate(90, 77, 148);
                $pdf->SetFillColor(255, 255, 255);
                $pdf->SetTextColor(2, 101, 203);
				$pdf->writeHTML($name,true,true,true,true,'R');
				$pdf->StopTransform();

                /*
                 * set icons if exist
                 */
                //print_r($dataobject->verwertungsrichtung);
                $this->getIcons($dataobject->verwertungsrichtung);

				// Set some content to print
				$pdf->SetFont('helvetica', '', 9, '', true);
                $pdf->SetTextColor(64, 64, 64);
				$pdf->writeHTMLCell($w=0, $h=0, $x='40', $y='75', $html, $border=0, $ln=1, $fill=0, $reseth=true, $align='', $autopadding=false);
				// ---------------------------------------------------------
				$pdf->Output('Solana-'.$dataobject->name_de.'.pdf', 'I');
				//produktiv dann aendern
				//$pdf->Output('example_001.pdf', 'FD');
			}
			else
			{
				echo "Fehler";
			}
		}
	}
}

?>